# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022/9/1
# @Author  : moe@miku39.fun
# @File    : AnimeFilm.py
# @Software: PyCharm
import re

import requests

from bili.service.VideoAbstraction import VideoAbstraction


class AnimeFilm(VideoAbstraction):
    def __init__(self, sess):
        super().__init__(sess)

    def getVideoInfo(self, video):
        url = "https://api.bilibili.com/pgc/view/web/season"
        params = {
            video["idType"]: video["videoID"],
        }
        response = requests.get(url=url, params=params).json()
        if response["code"] == 0:
            return {
                "title": re.sub(r'[:*?"<>| ]', "-", response["result"]["title"]),
                "pages": [
                    page for page in response["result"]["episodes"] if page["badge_type"] == 0
                ],
            }
        else:
            return False

    def getVideoPageInfo(self, dic):
        url = "https://api.bilibili.com/pgc/player/web/playurl"
        params = {
            "avid": dic["aid"],
            "cid": dic["cid"],
            "qn": 0,
            "fnver": 0,
            "fnval": 4048,
            "fourk": 1,
            "ep_id": dic["id"],
        }
        response = self.sess.get(url=url, params=params).json()
        if response["code"] == 0:
            videos = []
            tempSet = []
            for each in response["result"]["dash"]["video"]:
                self.allowVideoSet.add(each["id"])  # 获取指定视频号下的所有子视频清晰度
                if each["id"] not in tempSet:
                    tempSet.append(each["id"])
                    videos.append(
                        {
                            "id": each["id"],
                            "quality": self.videoQuality.get(each["id"]),
                            "videoURLs": AnimeFilm.getSourceList(each),
                        }
                    )
            audios = [
                {
                    "id": each["id"],
                    "quality": self.audioQuality.get(each["id"]),
                    "audioURLs": AnimeFilm.getSourceList(each),
                }
                for each in response["result"]["dash"]["audio"]
            ]
            self.videoSourceList.append(
                {
                    "title": re.sub(
                        r'[:*?"<>| ]', "-", f"{dic['title']}-{dic['long_title']}"
                    ),
                    "video": videos,  # 过滤相同画质视频源
                    "audio": audios,  # 音频源
                }
            )
        elif response["code"] == -412:
            print(response["message"])
            exit(1)
